﻿using System;
using System.IO;
using System.Net;
using Ionic.Zip;
using NeuralStock.Common;
using NeuralStock.DomainService.Interfaces;
using NeuralStock.Entities;
using NeuralStock.Tools;
using NeuralStock.DataAccess;
using System.Linq;

namespace NeuralStock.DomainService.Implementation
{
    public class BossaImportService : BaseService, IBossaImportService
    {
        private static string _zipPath = Path.Combine(DirectoryRepository.BossaDataDirectory, "mstcgl.zip");
        private static string _quotationsPath = Path.Combine(DirectoryRepository.BossaDataDirectory, "Quotations");
        private static string _downloadPath = @"http://bossa.pl/pub/ciagle/mstock/mstcgl.zip";

        ICompanyQuotationService quotationService;
        ICompanyService companyService;
        IFinancialReportService financialReportService;

        public BossaImportService(ICompanyQuotationService quotationService, ICompanyService companyService, IFinancialReportService financialReportService)
        {
            this.quotationService = quotationService;
            this.companyService = companyService;
            this.financialReportService = financialReportService;
        }

        public void ImportData() 
        {
            ImportQuotations();
        }

        public void ImportQuotations()
        {
            DownloadCurrentFiles();
            ImportQuotationsFromDownloadedFiles();
        }

        private void DownloadCurrentFiles()
        {
            if (File.Exists(_zipPath))
            {
                File.Delete(_zipPath);
            }

            WebClient webClient = new WebClient();
            webClient.DownloadFile(_downloadPath, _zipPath);

            if (Directory.Exists(_quotationsPath))
            {
                Directory.Delete(_quotationsPath, true);
            }

            Directory.CreateDirectory(_quotationsPath);

            using (ZipFile zipFile = ZipFile.Read(_zipPath))
            {
                zipFile.ExtractAll(_quotationsPath);
            }
        }

        private void ImportQuotationsFromDownloadedFiles()
        {
            foreach (string filePath in Directory.GetFiles(_quotationsPath))
            {
                string companyName = Path.GetFileNameWithoutExtension(filePath);

                if (companyService.Get(companyName) != null)
                {
                    int companyId = companyService.Get(companyName).Id;

                    var financialReports = financialReportService.GetAllForCompany(companyId).ToList();
                    if (financialReports.Count() == 0)
                    {
                        //continue; // temporary in order to not import quotes for companies withour financial reports
                    }

                    CsvReader<CompanyQuotationData> csvReader = new CsvReader<CompanyQuotationData>(new CompanyQuotationData());
                    var results = csvReader.GetDataFromCsv(filePath, true);

                    foreach (var result in results)
                    {
                        if (!result.IsValid())
                        {
                            return;
                        }
                        if (!quotationService.QuotationExists(companyId, result.Date.Value))
                        {
                            quotationService.CreateQuotation(companyId, result.Date.Value, result.Price.Value);
                            Console.WriteLine("Imported: {0}, {1} {2}", companyName, result.Date.Value, result.Price.Value);
                        }
                    }
                }
            }
        }
    }
}
